package com.xwli.springcloud.controller;

import com.xwli.springcloud.projo.Dept;
import com.xwli.springcloud.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author xwli
 * @date: 2021/9/6 20:55
 * @desc  提供RestFul服务
 * @since JDK 1.8
 */

@RestController
public class DeptController {

    @Autowired
    private DeptService deptService;
    //获取一些配置的信息，得到具体的微服务
    @Autowired
    private DiscoveryClient discoveryClient;

    @PostMapping("/dept/add")
    public boolean addDept(@RequestBody Dept dept){
        return deptService.addDept(dept);
    }

    @GetMapping("/dept/get/{deptNo}")
    public Dept getDeptByDeptNo(@PathVariable("deptNo") Long deptNo){
        return deptService.getDeptByDeptNo(deptNo);
    }

    @GetMapping("/dept/list")
    public List<Dept> getDeptAll(){
        return deptService.getDeptAll();
    }

    @GetMapping("/discovery/server")
    public Object discoveryMicroServer(@RequestParam("name") String applicationName){
        //获取微服务列表的清单
        List<String> services = discoveryClient.getServices();
        System.out.println("发现微服务==============>:\n"+services);

        //通过微服务id，applicationName，得到一个具体的微服务信息
        List<ServiceInstance> instances = discoveryClient.getInstances(applicationName);
        for (ServiceInstance instance : instances) {
            System.out.println(
                    "打印服务信息\n"+
                    instance.getHost()+"\t"+
                    instance.getPort()+"\t"+
                    instance.getUri()+"\t"+
                    instance.getServiceId()+"\t"
            );
        }
        return instances;
    }
}

